package com.geintech.learnobj;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Controller
public class ProviderController {

    @Resource
    private DefaultMQProducer defaultMQProducer;
    @Value("${apache.rocketmq.topic}" )
    private String topic;
    @Value( "${apache.rocketmq.tag}" )
    private String tag;


    @GetMapping("/regUser")
    public void registerUser(@RequestParam("username") String username,@RequestParam("password") String password) {
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("provider");
        // 设置NameServer的地址
        producer.setNamesrvAddr("rockmqserv:9876");
        //启动Producer实例
        try {
            producer.start();
            for(int i = 0; i < 10; i++){
                Message msg = new Message(topic , "TagA" , (username+','+password).getBytes(StandardCharsets.UTF_8));
                //发送消息到一个Broker
                SendResult sentResult = producer.send(msg);
                //通过sentResult返回消息是否成功发送
                System.out.printf("%s%n", sentResult);
            }
        }
        catch(Exception e) {

        }
        //如果不再发送消息，关闭Producer实例
        producer.shutdown();
    }


}
